package com.smarthome.connect;

import android.util.Log;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

import com.smarthome.BoxAndroidNew.LocalData;


 
public class TCPClient {
 
    public static String serverMessage;
    public static final String SERVERIP = LocalData.IP_Anddress;
    //your computer IP address
    public static final int SERVERPORT = 11008;
    public static OnMessageReceived mMessageListener = null;
    private boolean mRun = false;
 
    PrintWriter out;
    BufferedReader in;
 
    /**
     *  Constructor of the class. OnMessagedReceived listens for the messages received from server
     */
    public TCPClient(OnMessageReceived listener) {
        mMessageListener = listener;
    }
 
    /**
     * Sends the message entered by client to the server
     * @param message text entered by client
     */
    public void sendMessage(String message){
        if (out != null && !out.checkError()) {
            out.println(message);
            out.flush();
        }
    }
 
    public void stopClient(){
        mRun = false;
    }
 
    public void run(String ip, int port) { 
        mRun = true; 
        try {
            //here you must put your computer's IP address.
            InetAddress serverAddr = InetAddress.getByName(ip);        
            //create a socket to make the connection with the server
            Socket socket = new Socket(serverAddr, port);
//            socket.setSoTimeout(4000);
            Log.d("TCP Clients", "C: Connecting..."); 
            try {
                //send the message to the server
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                Log.i("TCP Clients", "C: Done.");
                //receive the message which the server sends back
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                LocalData.isConnectsuccess = true;
                //in this while the client listens for the messages sent by the server
                while (mRun) {
                    serverMessage = in.readLine();
 
                    if (serverMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(serverMessage);
                    }
                    serverMessage = null;
                    Log.i("TCP Clients", "C: in mRun." +serverMessage );
                } 
                Log.i("TCP Clients", "S: Received Message: '" + serverMessage + "'");                
               
            } catch (Exception e) {
                Log.e("TCP Clients", "S: Error", e);
                LocalData.isConnectsuccess = false;
            } finally {
                //the socket must be closed. It is not possible to reconnect to this socket
                // after it is closed, which means a new socket instance has to be created.
                socket.close();
            }
 
        } catch (Exception e) {
 
            Log.e("TCP Clients", "C: Error", e);
            LocalData.isConnectsuccess = false;
        }
 
    }
 
    //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
    //class at on asynckTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }
}